﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Quartz;
using ZHDJ.Core.Log;
using ZHDJ.Data;
using ZHDJ.WinService.Util;
using MySqlHelper = ZHDJ.Data.MySqlHelper;

namespace ZHDJ.WinService.Job
{
    /// <summary>
    /// 执行存储过程
    /// </summary>
    public class RunProcedureJob : JobBase
    {
        public string JobFlag { get; set; }
        public string JobName { get; set; }
        public string JobSql { get; set; }

        public string JobCron { get; set; }

        public RunProcedureJob()
        {
            JobName = "";
            JobSql = "";
            JobCron = "";
            JobFlag = "";
        }

        public RunProcedureJob(string jobFlag, string jobName, string jobSql, string jobCron)
        {
            JobName = jobName;
            JobSql = jobSql;
            JobCron = jobCron;
            JobFlag = jobFlag;
        }

        /// <summary>
        /// 执行业务锁
        /// </summary>
        private static Object BusinessLock = new Object();
        public override JobSetInfo JobSetInfo
        {
            get
            {
                return new JobSetInfo()
                {
                    JobGroup = JobFlag + "Group",
                    JobName = JobFlag + "Job",
                    TriggerName = JobFlag + "Trigger",
                    Cron = JobCron
                };
            }
        }


        public override void RunBusiness(IJobExecutionContext context)
        {
            try
            {
                
               
                lock (BusinessLock)
                {
                    var job = ScheduleHelper.RunProcedureJobList.FirstOrDefault(a => a.JobFlag + "Job" == context.JobDetail.Key.Name);
                    if (job == null)
                    {
                        return;
                    }
                    LogHelper.Info("执行定时作业：" + job.JobName, "ScheduledJob");
                    if (!string.IsNullOrEmpty(job.JobSql))
                    {
                        LogHelper.Info(job.JobSql);
                        MySqlHelper.ExecuteNonQuery(job.JobSql);
                    }
                    
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
        }

    }
}
